package org.dru.clay.util.functional;

import java.util.Iterator;

/**
 * Iterators
 * User: joakimd
 * Date: 2013-07-24
 * Time: 14:21
 */
public final class Iterators {
    private Iterators() {
    }

    public static <T> Iterator<T> filter(final Iterator<T> source, final Predicate<T> predicate) {
        return new AbstractIterator<T>() {
            @Override
            protected T computeNext() {
                while (source.hasNext()) {
                    final T value = source.next();
                    if (predicate.apply(value)) {
                        return value;
                    }
                }
                return setDone();
            }

            @Override
            public void remove() {
                setError();
                source.remove();
                setNotReady();
            }
        };
    }
}
